<<<<<<< HEAD
import numpy
from PIL import Image
import scipy.special
import numpy as np
import matplotlib.pyplot

def cut(filename, savefile, row, col):
    img = Image.open(filename)
    width, height = img.size
    w = width // col
    h = height // row
    threshold = 80

    cnt = 0
    rec = []
    for r in range(row):
        for c in range(col):
            box = (c * w, r * h, (c + 1) * w, (r + 1) * h)
            timg = img.crop(box).convert('L')
            #timg.save(str(cnt) + ".jpg")
            timg = timg.resize((28, 28))
            table = []
            for i in range(256):
                if i < threshold:
                    table.append(255)
                else:
                    table.append(0)

            photo = list(timg.point(table, '1').getdata())
            #num = int(input("请输入第" + str(cnt) + "数字是什么："))
            photo.insert(0, r)
            #print(photo)
            timg.point(table, '1').save("dl/" + str(cnt) + ".jpg")
            np.set_printoptions(threshold=np.inf)
            table = np.reshape(np.array(photo), (1, 785))
            rec.append(table)
            cnt += 1
    file = open(savefile + "1" + ".csv", 'w')
    # 遍历矩阵，将numpy读出
    for item in rec:
        for iitem in item:
            file.write(','.join(str(i) for i in iitem))  # numpyInt64->int->str
        file.write("\n")
    file.close()

#neural network class definition
class neuralNetwork:
    #初始化
    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate ):
        #设置每层节点数
        self.inodes = inputnodes
        self.hnodes = hiddennodes
        self.onodes = outputnodes

        #设置权值矩阵 wih, who
        self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes))
        self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes))

        #设置学习率
        self.lr = learningrate

        #激活函数是S函数
        self.activation_function = lambda x: scipy.special.expit(x)

        pass

    #训练
    def train(self, inputs_list, targets_list):
        #将输入列表和目标列表转化为矩阵
        inputs = numpy.array(inputs_list, ndmin=2).T
        targets = numpy.array(targets_list, ndmin=2).T

        #计算隐藏层信号
        hidden_inputs = numpy.dot(self.wih, inputs)
        hidden_outputs = self.activation_function(hidden_inputs)

        #计算输出层信号
        final_inputs = numpy.dot(self.who, hidden_outputs)
        final_outputs = self.activation_function(final_inputs)
        #计算error
        output_errors = targets - final_outputs
        hidden_errors = numpy.dot(self.who.T, output_errors)

        #进行权重的更新
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)),
                                        numpy.transpose(hidden_outputs))
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)),
                                        numpy.transpose(inputs))
        pass

    #询问
    def query(self, inputs_list):
        #将输入列表转为矩阵
        inputs = numpy.array(inputs_list, ndmin=2).T

        #计算隐藏层
        hidden_inputs = numpy.dot(self.wih, inputs)
        hidden_output = self.activation_function(hidden_inputs)

        #计算输出层
        final_inputs = numpy.dot(self.who, hidden_output)
        final_outputs = self.activation_function(final_inputs)

        return final_outputs

def neuralnetwork(filename):
    cut(filename, "dl/preparationData/testData/Data/mytestData", 1, 6)

    #设置节点数
    input_nodes = 784
    hidden_nodes = 100
    output_nodes = 10

    #设置学习率
    learning_rate = 0.2

    #创建神经网络对象
    n = neuralNetwork(input_nodes,hidden_nodes,output_nodes,learning_rate)
    #读入训练数据
    training_data_file = open("dl/trainingData/mnist_train.csv", 'r')
    training_data_list = training_data_file.readlines()
    training_data_file.close()
    print("reading training file")
    generation = 2
    for g in range(generation):
        #进行训练
        print("generation: " + str(g))
        for record in training_data_list:
            all_values = record.split(',')
            inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
            targets = numpy.zeros(output_nodes) + 0.01
            targets[int(all_values[0])] = 0.99
            n.train(inputs, targets)

    test_data_file = open("dl/preparationData/testData/Data/mytestData1.csv", 'r')
    test_data_list = test_data_file.readlines()
    test_data_file.close()

    ans = ""
    scoreboard = []
    for record in test_data_list:
        all_values = record.split(',')
        correct_label = int(all_values[0])
        inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
        outputs = n.query(inputs)
        label = numpy.argmax(outputs)
        print("识别结果:" + str(label), "期望结果: " + str(correct_label))
        if (label == correct_label):
            scoreboard.append(1)
        else:
            scoreboard.append(0)
        ans = ans + str(label)
    print("识别准确率:" + str(sum(scoreboard) / len(scoreboard)))
    print(ans)
    return ans


if __name__ == '__main__':
    res = neuralnetwork("preparationData/testData/img/1.png")
    print(res)
=======
import numpy
import scipy.special
import matplotlib.pyplot


# neural network class definition
class neuralNetwork:
    # 初始化
    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
        # 设置每层节点数
        self.inodes = inputnodes
        self.hnodes = hiddennodes
        self.onodes = outputnodes

        # 设置权值矩阵 wih, who
        self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5), (self.hnodes, self.inodes))
        self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5), (self.onodes, self.hnodes))

        # 设置学习率
        self.lr = learningrate

        # 激活函数是S函数
        self.activation_function = lambda x: scipy.special.expit(x)

        pass

    # 训练
    def train(self, inputs_list, targets_list):
        # 将输入列表和目标列表转化为矩阵
        inputs = numpy.array(inputs_list, ndmin=2).T
        targets = numpy.array(targets_list, ndmin=2).T

        # 计算隐藏层信号
        hidden_inputs = numpy.dot(self.wih, inputs)
        hidden_outputs = self.activation_function(hidden_inputs)

        # 计算输出层信号
        final_inputs = numpy.dot(self.who, hidden_outputs)
        final_outputs = self.activation_function(final_inputs)
        # 计算error
        output_errors = targets - final_outputs
        hidden_errors = numpy.dot(self.who.T, output_errors)

        # 进行权重的更新
        self.who += self.lr * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)),
                                        numpy.transpose(hidden_outputs))
        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)),
                                        numpy.transpose(inputs))
        pass

    # 询问
    def query(self, inputs_list):
        # 将输入列表转为矩阵
        inputs = numpy.array(inputs_list, ndmin=2).T

        # 计算隐藏层
        hidden_inputs = numpy.dot(self.wih, inputs)
        hidden_output = self.activation_function(hidden_inputs)

        # 计算输出层
        final_inputs = numpy.dot(self.who, hidden_output)
        final_outputs = self.activation_function(final_inputs)

        return final_outputs


if __name__ == "__main__":
    # 设置节点数
    input_nodes = 784
    hidden_nodes = 100
    output_nodes = 10

    # 设置学习率
    learning_rate = 0.3

    # 创建神经网络对象
    n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
    # 读入训练数据
    training_data_file = open("trainingData/mnist_train.csv", 'r')
    training_data_list = training_data_file.readlines()
    training_data_file.close()
    print("reading training file")
    generation = 3
    for g in range(generation):
        # 进行训练
        print("generation: " + str(g))
        for record in training_data_list:
            all_values = record.split(',')
            inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
            targets = numpy.zeros(output_nodes) + 0.01
            targets[int(all_values[0])] = 0.99
            n.train(inputs, targets)

    test_data_file = open("preparationData/testData/Data/mytestData1.csv", 'r')
    test_data_list = test_data_file.readlines()
    test_data_file.close()

    scorecard = []
    for record in test_data_list:
        all_values = record.split(',')
        correct_label = int(all_values[0])
        print(correct_label, "correct label")
        inputs = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
        outputs = n.query(inputs)
        label = numpy.argmax(outputs)
        print(label, "network's answer")
        if (label == correct_label):
            scorecard.append(1)
        else:
            scorecard.append(0)
    print(sum(scorecard) / len(scorecard))

'''
    all_values = data_list[0].split(',')
    image_array = numpy.asfarray(all_values[1:]).reshape((28, 28))
    matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')
    matplotlib.pyplot.show()
    #print(n.query([1.0, 0.5, -1.5]))
'''
>>>>>>> f5d1e027a35ed630836ffc3173372ec165635847
